package cn.com.generaldata.os.service.indicator_evaluation.prosperity_analysis;

import org.apache.commons.lang3.Validate;

import cn.com.generaldata.jsme_indicator_system.entity.IndicatorEvaluation;
import cn.com.generaldata.jsme_indicator_system.util.Constants;
import cn.com.generaldata.os.service.indicator_constant.ProvinceIndicatorConstant;
import cn.com.generaldata.os.service.indicator_evaluation.IndicatorEvaluationCalculateService;
import cn.com.generaldata.os.util.BeanMapper;
import cn.com.generaldata.os.vo.IndicatorAccountVO;

/**
 * CPI相关指标增长率评估指标计算类.
 */
public class CPIRelateGrowthRateCalculateService extends IndicatorEvaluationCalculateService {

	private String CPIIndicatorName = "CPI";

	@Override
	protected Double calculate(IndicatorEvaluation indicator, IndicatorAccountVO indicatorAccountVO) {
		Double result = null;
		if (indicator.getSection() == Constants.INDICATOR_LEVEL_PROVINCE) {
			result = calculateProvinceResult(indicator, indicatorAccountVO);
		} else if (indicator.getSection() == Constants.INDICATOR_LEVEL_CITY) {
			// 市指标没确定先保留
		}
		return result;
	}

	/**
	 * 计算江苏省进出口总额增长率评估指标计算类.
	 * 
	 * @param indicator
	 * @param indicatorAccountVO
	 * @return
	 */
	private Double calculateProvinceResult(IndicatorEvaluation indicator, IndicatorAccountVO indicatorAccountVO) {
		Double sourceIndicatorCurrentPrice = getSourceIndicatorCurrentPrice(indicatorAccountVO,
				indicatorAccountVO.getYear(), indicator);
		Double cpi = getCPI(indicatorAccountVO);

		Double sourceIndicatorComparePrice = sourceIndicatorCurrentPrice * 100 / cpi;

		Double lastSourceIndicatorCurrentPrice = getSourceIndicatorCurrentPrice(indicatorAccountVO,
				indicatorAccountVO.getYear() - 1, indicator);

		return sourceIndicatorComparePrice / lastSourceIndicatorCurrentPrice - 1;
	}

	/**
	 * 获得源指标现价
	 * 
	 * @param indicatorAccountVO
	 * @return
	 */
	private Double getSourceIndicatorCurrentPrice(IndicatorAccountVO indicatorAccountVO, int year,
			IndicatorEvaluation indicator) {
		Double currentPrice = 0d;
		IndicatorAccountVO vo = BeanMapper.map(indicatorAccountVO, IndicatorAccountVO.class);
		for (String areaId : ProvinceIndicatorConstant.CITYS) {
			vo.setAreaId(areaId);
			Double sourceVal = getInputOrAccountingIndicatorValue(vo, year, indicator.getReference());
			Validate.isTrue(sourceVal != null);
			currentPrice += sourceVal;
		}
		return currentPrice;
	}

	private Double getCPI(IndicatorAccountVO indicatorAccountVO) {

		Double cpi = getInputOrAccountingIndicatorValue(indicatorAccountVO, indicatorAccountVO.getYear(),
				CPIIndicatorName);

		Validate.isTrue(cpi != null);

		return cpi;
	}

}
